<template>
  <div class="app-container">
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        width="50"
      />
      <el-table-column label="ID" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员ID">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="之前等级">
        <template slot-scope="{row}">
          <span v-if="row.old">{{ row.old.display }}</span>
        </template>
      </el-table-column>
      <el-table-column label="现在等级">
        <template slot-scope="{row}">
          <span v-if="row.new">{{ row.new.display }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template slot-scope="{row}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ row.update_time | timeFilter }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
import config from '@/config'

const initQuery = {
  status: config.news.OPEN,
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'NewsList',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.news.statusText(+status)
    },
    homeText(v) {
      return +v === 1 ? '是' : ''
    }
  },
  data() {
    return {
      // 状态
      status: {},
      // 状态
      statusMap: [],
      // 显示帮助提示
      showHelp: false,
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {},
      selectionList: []
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getList()
  },
  methods: {
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      api.member.down({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
      }).finally(() => {
        this.listLoading = false
      })
    },
    refresh() {
      this.$router.push({
        path: '/member/down',
        query: this.listQuery
      })
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      this.status = config.brand
    },
    /**
     * 导出
     */
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            // return config.news.statusText(+v['status'])
            return this.$options.filters['statusText'](v[j])
          }
          return v[j]
        }))
      }
      this.listLoading = true
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      const response = await api.news.list({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '标题', '状态', '上传时间', '修改时间', '排序']
        const filterVal = ['id', 'title', 'status', 'create_time', 'update_time', 'sort']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '新闻列表'
        })
      })
      this.listLoading = false
    },
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>
